<template>
  <el-form
    ref="registerForm"
    :model="registerUser"
    :rules="registerRules"
    label-width="100px"
    class="registerForm sign-up-form"
  >
    <el-form-item label="用户名" prop="name">
      <el-input v-model="registerUser.name" placeholder="输入用户名"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="registerUser.email" placeholder="输入邮箱"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        v-model="registerUser.password"
        type="password"
        placeholder="输入密码"
      ></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="password2">
      <el-input
        v-model="registerUser.password2"
        type="password"
        placeholder="再次输入密码"
      ></el-input>
    </el-form-item>

    <el-form-item label="选择身份">
      <el-select v-model="registerUser.role" placeholder="请选择身份">
        <el-option label="管理员" value="admin"></el-option>
        <el-option label="用户" value="user"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button
        @click="handleRegister('registerForm')"
        type="primary"
        class="submit-btn"
        >注册</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import { registerUser, registerRules } from "@/utils/RegisterValidator";
export default {
  data() {
    return { registerUser, registerRules };
  },
  methods: {
    handleRegister(loginForm) {
      this.$refs[loginForm].validate((valid) => {
        if (valid) {
          this.$axios
            .post("/api/register", this.registerUser)
            .then((res) => {
              console.log(res)
              if (res.data.success) {
                this.$store.commit("setuser_info",res.data.user_info)
                this.$message.success("注册成功");
                this.$router.replace("/");
              } else {
                this.$message.warning(res.data.msg);
              }
            });
          }
      });
    },
  },
};
</script>
<style scoped>
.registerForm {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px 40px 20px 20px;
  border-radius: 5px;
  box-shadow: 0px 5px 15px #ddd;
}

.submit-btn {
  width: 100%;
}
</style>
